package com.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.bean.*;
import com.service.*;
import com.util.AlipayConfig;
import com.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class AlipayController {


    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CdyOrderService cdyOrderService;
    @Autowired
    private BookingService bookingService;
    @Autowired
    private MovieService movieService;
    @Autowired
    private FilmsService filmsService;
    @Autowired
    private SeatService seatService;

    private Date date = new Date();

    @RequestMapping("alipay")
    public void alipay(HttpServletResponse httpResponse, Commodity commodity, String subtotal, String count, String id
                       )
            throws IOException {
        System.out.println("-------------------alipay");
        System.out.println(commodity);
        System.out.println(subtotal);
        System.out.println(count);
        System.out.println(id);
        System.out.println("*********************************");

        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAY_URL, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY,
                AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(AlipayConfig.RETURN_URL);
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString()+","+id;
        //付款金额，必填
        String total_amount;
        total_amount  = subtotal;

        //订单名称，必填
        List<Commodity> commodities = commodityService.find(commodity);
        String subject = commodities.get(0).getCdyName();
        //商品描述，可空
        String body = "尊敬的会员欢迎购买"+commodities.get(0).getCdyName();
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"id\":\""+ commodities.get(0).getId() +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping("alipayTicket")
    public void alipayTicket(HttpServletResponse httpResponse,String subtotal,String MovieId,String length,String myseat,String hall,String id)
            throws IOException {
        System.out.println("-------------------alipay");
        System.out.println(subtotal);
        System.out.println("*********************************");

        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAY_URL, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY,
                AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(AlipayConfig.RETURN_URL);
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL);

        Double subtotal1 = 0.0;
        if (myseat != null && hall != null && MovieId != null && length != null){
            //保存预购订单
            String[] split = myseat.split(",");
            int save = 0;
            for (int i = 0; i <split.length ; i++) {
                String[] split1 = split[i].split("-");
                String hang = split1[0];
                String lie = split1[1];
                //获取到所选的电影信息
                List<Movie> m = movieService.find(new Movie(Integer.valueOf(MovieId)));
                //获取到所选的排片信息
                List<Films> f = filmsService.find(new Films(Integer.valueOf(id)));;
                Booking booking = new Booking();
                //设置订单状态
                booking.setState(3);
                //设置订单行
                booking.setRows(Integer.valueOf(hang));
                //设置订单列
                booking.setNumber(Integer.valueOf(lie));
                //设置订单电话
                booking.setPhone("15735182312");
                //设置订单影厅号
                booking.setHall(Integer.valueOf(hall));
                //设置订单影片开始时间
                booking.setTime(f.get(0).getStartTime());
                //设置订单下单时间
                booking.setOrderTime(date);
                //设置订单价格
                booking.setPrice(f.get(0).getPrice());
                booking.setMovieName(MovieId);

                //查询出来对应的座位号
                Seat seat = new Seat();
                seat.setCinemaId(Integer.valueOf(hall));
                seat.setRows(Integer.valueOf(hang));
                seat.setNumber(Integer.valueOf(lie));
                List<Seat> seats = seatService.find(seat);
                //备用字段设座位编号
                booking.setSpare(seats.get(0).getId());
                System.out.println("这是准备添加的订单:"+booking);
                bookingService.save(booking);
                save += 1;
                System.out.println("添加的电影票订单数: "+ save);
            }
            //获取到所选的排片信息
            List<Films> f = filmsService.find(new Films(Integer.valueOf(id)));
            subtotal1 = save*f.get(0).getPrice();
        }


        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount;
        if (subtotal != null){
            total_amount  = subtotal;
        }else{
            total_amount = subtotal1.toString();
        }
        //订单名称，必填
        String subject = "七匹狼电影购票";
        //商品描述，可空
        String body = "尊敬的会员欢迎来七匹狼电影院观影";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @GetMapping("alipayReturnNotice")
    public String alipayReturnNotice(HttpServletRequest request, HttpServletResponse response, Commodity commodity,
                                     CdyOrder cdyOrder, String id)
            throws IOException, AlipayApiException, ParseException {

        System.out.println("支付成功, 进入同步通知接口...");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }
        //查看参数都有哪些
        System.out.println(params);
        // 调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
//            String id = new String(request.getParameter("id").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println(id);
            System.out.println("********************** 支付成功(支付宝同步通知) **********************");
            System.out.println("* 商户订单号: "+out_trade_no);
            System.out.println("* 支付宝交易号: "+trade_no);
            System.out.println("* 付款金额: "+total_amount);
            System.out.println("*********************************************************************");


            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            String[] split = out_trade_no.split(",");

            if(split.length > 1){
                String s = split[1];
                commodity.setId(Integer.valueOf(s));

                List<Commodity> commodities = commodityService.find(commodity);
                cdyOrder.setCdyName(commodities.get(0).getId());
                cdyOrder.setPrice(commodities.get(0).getPrice());

                cdyOrder.setTotalPrice(Double.valueOf(total_amount));
                double count = Double.valueOf(total_amount)/commodities.get(0).getPrice();

                Double reseve3 = Double.parseDouble(String.valueOf(count));
                int b=reseve3.intValue();
                Integer rentCount=Integer.valueOf(b);

                cdyOrder.setNumber(rentCount);

                cdyOrder.setPhone("15735182312");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
                cdyOrder.setOrderTime(simpleDateFormat.parse(format));
                cdyOrder.setState(0);
                System.out.println(cdyOrder+"******************这是生成的订单");
                cdyOrderService.save(cdyOrder);
                System.out.println(commodities.get(0).toString()+"************第一次的");


                Integer stock = commodities.get(0).getStock();
                int num = (int) (stock- count);
                commodities.get(0).setStock(num);
                System.out.println(commodities.get(0).toString()+"***********************第二次计算后的");
                //修改库存
                commodityService.modify(commodities.get(0));
            }else{
                Booking booking = new Booking();
                booking.setPhone("15735182312");
                booking.setOrderTime(date);
                List<Booking> bookings = bookingService.find(booking);
                System.out.println(bookings+"查到的刚刚添加进去的订单");
                System.out.println("<><><><><><><><><购票成功,接下来就是修改状态代码:");

                //查询到排片信息时间+影厅号
                Films film = new Films();
                film.setCinemaId(bookings.get(0).getHall());
                film.setStartTime(bookings.get(0).getTime());
                //查询到的具体排片信息
                List<Films> films = filmsService.find(film);
                System.out.println(films);
                System.out.println(films.get(0).toString());

                System.out.println(bookings.size()+"订单个数");
                for (int i = 0; i <bookings.size(); i++) {
                    Booking booking1 = bookings.get(i);
                    //修改状态
                    booking1.setState(0);
                    int modify = bookingService.modify(booking1);
                    System.out.println("修改状态成功+"+modify);

                    Seat seat = new Seat();
                    //添加座位表的选中信息
                    seat.setCinemaId(booking1.getHall());
                    seat.setRows(booking1.getRows());
                    seat.setNumber(booking1.getNumber());
                    //找到该座位信息
                    List<Seat> seats = seatService.find(seat);
                    System.out.println("><><><+_+_+_+_+这是seat信息:"+seats.get(0));
                    seat.setId(seats.get(0).getId());
                    //判断是否该座位有多个电影要播放

                    if(seats.get(0).getChoose() == null){
                        seat.setChoose(films.get(0).getId()+"");
                    }else{
                        seat.setChoose(seats.get(0).getChoose()+","+films.get(0).getId());
                    }

                    int modify1 = seatService.modify(seat);
                    System.out.println(seat+"---"+modify1+"+ 修改座位选中状态成功!");
                }
            }

        }else{
            System.out.println("支付, 验签失败...");
        }

        return "redirect:/ok.html";//跳转付款成功页面
    }

    @PostMapping("alipayNotifyNotice")
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response,
                                     Commodity commodity, String subtotal, CdyOrder cdyOrder, String count

    ) throws Exception {

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);

        //——请在这里编写您的程序（以下代码仅作参考）——
        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if(signVerified) {//验证成功
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            List<Commodity> commodities = commodityService.find(commodity);
            cdyOrder.setCdyName(commodities.get(0).getId());
            cdyOrder.setPrice(commodities.get(0).getPrice());
            cdyOrder.setNumber(Integer.valueOf(count));
            cdyOrder.setTotalPrice(Double.valueOf(subtotal));
            cdyOrder.setPhone("15735182312");
            cdyOrder.setOrderTime(new Date());

            System.out.println(cdyOrder+"******************这是生成的订单");
        }else{


        }
        return "suc";
    }
}
